import Vue from 'vue'
import Vuex from 'vuex'

import {updateUserinfo} from '../api/requestapi'

Vue.use(Vuex)

const store= new Vuex.Store({
  state: {
    userdata: {
      userName:'',
      name: '未登陆',
      userEmail: '',
      userSign: '',
      userPhone:'',
    }||sessionStorage.getItem('userinfo') ,
    userImgUrl: sessionStorage.getItem('userImgUrl')||''
  },

  //
  getters: {
    //获取用户的基本信息
    getUserdata: (state) => {
      
      //把取出的对象字符串进行转化为对象
     var data = JSON.parse(sessionStorage.getItem('userinfo'))
      if (data == null) {
        return state.userdata;
      }
      state.userdata=data;

      return state.userdata;
    },
    //获取用户的头像信息
    getUserImgUrl: (state) => {
      return state.userImgUrl;
    }
  },
 

 //同步操作
  mutations: {

    //重新设置用户基本信息
    setUserdata(state, userdata) {
      //把对象存储转化为字符串  sessionstorage 存储的对象无法直接用
      sessionStorage.setItem('userinfo', JSON.stringify(userdata));
      sessionStorage

      state.userdata = userdata;
    },

     //重新设置用户头像地址
    setUserImgUrl(state, userImgUrl) {
      sessionStorage.setItem('userImgUrl', userImgUrl);
      state.userImgUrl = userImgUrl;
    }
     


  },

  //异步操作 （涉及到数据库操作）
  actions: {

    updateUserinfo(context,userinfo) {
      console.log('收到的参数' + userinfo);
      
      //把收到的参数先转化字符串
      var param = JSON.parse(JSON.stringify(userinfo))  ;
      
      console.log('转化后的参数')
      console.log(param)
      
      //先更新数据库 再提交
      updateUserinfo(param).then((response) => {
        if (response.code == 200) {
          this.state.userdata.name = userinfo.name;
          this.state.userdata.userSign = userinfo.userSign;
          this.state.userdata.userEmail = userinfo.userEmail;
          this.state.userdata.userPhone = userinfo.userPhone;
          context.commit('setUserdata', this.state.userdata);
        }
      })
        
      
    }


  },
  modules: {
  }
})
export default store
